<script setup lang="ts">
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import {useUserStoreWithOut} from "@/stores/modules/user";
import {ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {LOGIN_URL} from "@/config/config";
import SvgIcon from "@/components/SvgIcon/src/SvgIcon.vue";

const router = useRouter();
const route = useRoute()

const userStore = useUserStoreWithOut();
const { name, avatar } = userStore.userInfo || {}

const visible = ref(false)

const onChange = (show: boolean)=> {
    visible.value = show
}

const handleCommand = (commad: string) => {
    if (commad === 'logout') {
        logout();
    }
}
const logout = () => {
    ElMessageBox.confirm('您确定要退出吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then( async ()=>{
        await userStore.logout();
        router.push({path: LOGIN_URL, query:{redirect:route.fullPath}})
        ElMessage.success('退出登录成功')
    })
}

</script>

<template>
  <ElDropdown @visible-change="onChange" @command="handleCommand">
    <div class="avatar-dropdown">
        <img class="user-avatar" :src="avatar" alt="">
        <div class=""> {{ name }}</div>

        <ElIcon class="up-down">
          <component :is="visible ? 'ArrowUp' : 'ArrowDown'"></component>
        </ElIcon>
    </div>

      <template #dropdown>
          <el-dropdown-menu>
              <el-dropdown-item command="logout">
                  <svg-icon name="logout" size="16px"></svg-icon>
                  <span>退出登录</span>
              </el-dropdown-item>
          </el-dropdown-menu>
      </template>

  </ElDropdown>
</template>

<style scoped lang="scss">
.avatar-dropdown {
  display: flex;
  align-content: center;
  align-items: center;
  justify-content: center;
  justify-items: center;
  height: 50px;
  padding: 0 20px 0;

  .user-avatar {
    width: 40px;
    height: 40px;
    cursor: pointer;
    border-radius: 50%;
  }

  .user-name {
    position: relative;
    margin: 0 6px;
    cursor: pointer;
  }
}
</style>
